import moment from "moment"


const headers = {
  'Content-Type': 'application/json'
}

// const host = 'http://192.168.0.101:10880'
const host = ''

export const getApi = <T>(url: string, init?: RequestInit): Promise<T> => {
  return fetch(host+url, init)
    .then(response => {
      // console.log(response)
      if(response.status == 500){
        // console.log(response.json())
      }
      if (!response.ok) {
        throw new Error(response.statusText)
      }
      return response.json() as Promise<T>
    })
}

export const onHttp = async(parms: any,url:string)=>{
  
  let obj:any = {
      method: 'post',
      headers: headers
  }
  if(parms){
      obj.body = JSON.stringify(parms)
  }
  try {
      const response = await fetch(host+url,obj);
      if(response.status == 200){
          return response.json();
      }else{
          console.log('network error')
      }
  } catch(err) {
      console.log(err);
  }
}

export const onAdd = (address:string) => {
  if (address && address.length > 10) {
    return address.slice(0, 4) + '....' + address.substr(-4, 4)
  } else {
    return address
  }
}

export const onMomented = (item:any)=>{
  if(item){
    let time = moment.utc(item * 1000)
    return time.local().format('YYYY-MM-DD HH:mm')
  }
  return ''
}

export async function copyPlaintext(text: string): Promise<boolean> {
  try {
      if (navigator?.clipboard?.writeText) {
          await navigator.clipboard.writeText(text);
          return true;
      } else {
          const textArea = document.createElement("textarea");
          textArea.value = text;

          // Avoid scrolling to bottom
          textArea.style.top = "0";
          textArea.style.left = "0";
          textArea.style.position = "fixed";

          document.body.appendChild(textArea);
          const selection:any = document.getSelection();
          const range = document.createRange();
          // range.selectNodeContents(textArea);
          range.selectNode(textArea);
          selection.removeAllRanges();
          selection.addRange(range);

          const successful = document.execCommand("copy");
          selection.removeAllRanges();
          document.body.removeChild(textArea);
          return successful;
      }
  } catch (e) {
      console.log("copyPlaintext failed", e);
  }
  return false;
}

export const goAdd = (address:string)=>{
  let url = 'https://polkadot.subscan.io/account/'+ address
  window.open(url, "_blank");
}

export const goHash = (hash:string)=>{
  let url = 'https://polkadot.subscan.io/extrinsic/'+ hash
  window.open(url, "_blank");
}
